import axios from 'axios'

/**
 *  ##axios一系列封装 详情请参见axios文档  https://www.npmjs.com/package/axios
 *
 *  ##post数据需要格式化数据
 *  var qs = require('qs');
 *  axios.post('/foo', qs.stringify({ 'bar': 123 }));
 *
 *  ##post数组的时候 详见https://www.npmjs.com/package/qs
 *  qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false });
 *
 */
import qs from 'qs'
import store from '../store'
import * as ToastUtil from '../cubeui/toast'
const SUCCESS_CODE = process.env.VUE_APP_SUCCESS_CODE
const NOT_LOGIN_CODE = process.env.VUE_APP_NOT_LOGIN_CODE
axios.defaults.withCredentials = true //前后端分离session保持一致
let baseURL = process.env.VUE_APP_SERVER_URL
import router from '../router'
import {getToken} from "../cookie";
//配置
let service = axios.create({
    baseURL: baseURL,
    timeout: 15000,
    //这里可以免去 每次提交要qs.stringfy
    transformRequest: [function (data, headers) {
        // Do whatever you want to transform the data
        return qs.stringify(data, { indices: false })
    }],
})

//request监听器
service.interceptors.request.use(
    config => {
        // let token = store.getters.loginToken
        let token = getToken()
        if (token) {
            config.headers[process.env.VUE_APP_TOKEN_NAME] = token
        }
        return config
    },
    error => {
        return Promise.reject(error)
    })

//response监听器
service.interceptors.response.use(
    response => {
        //根据后端协议对返回接口格式进行处理 如 if(response.data.code==1000?)
        if(SUCCESS_CODE!=response.data.code){
            if(NOT_LOGIN_CODE==response.data.code){
                //没有登录
               router.push({
                   path:'/login'
               })
                // ToastUtil.showErrorToast("需要登陆!")
                return  Promise.reject("没有登陆!")
            }
            ToastUtil.showErrorToast("业务异常:"+response.data.msg)
            return Promise.reject("业务异常:"+response.data.msg)
        }
        return response.data;
    },
    error => {
        // console.log(error)
        ToastUtil.showErrorToast("系统错误!:"+error)
        return Promise.reject("系统错误!"+error);
    })
export default service
